package stateful;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * flink设置重启策略
 */
public class RestartStrategyDemo2 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> lines = env.socketTextStream("192.168.200.10", 8888);

        // 默认重启策略 RestartStrategies.noRestart()
        // 设置周期性的重启策略 30 内 小于3次就重启
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.seconds(30), Time.seconds(1)));

        lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                for (String word : s.split(" ")) {
                    if (word.contains("error")) {
                        throw new RuntimeException("出现错误数据!");
                    } else {
                        collector.collect(Tuple2.of(word, 1));
                    }
                }
            }
        }).keyBy(t -> t.f0)
                .sum(1)
                .print();

        env.execute("");
    }
}
